<template>
  <basic-container>
    <avue-crud
      :option="option"
      :search.sync="search"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @sort-change="sortChange"
      @on-load="onLoad"
    >
      <!--      <template slot="menuLeft">
              <el-button type="primary" icon="el-icon-plus" size="small" @click.stop="handleSave">新 建</el-button>

              <el-button
                type="danger"
                size="small"
                icon="el-icon-delete"
                plain
                v-if="permissionList.delBtn"
                @click="handleDelete"
              >解 绑
              </el-button>
            </template>-->
      <!-- <template slot="menuRight">
        <el-button
          type="success"
          size="small"
          plain
          icon="el-icon-upload2"
          v-if="permission.terminal_import"
          @click="handleImport"
          >导入
        </el-button>
        <el-button
          type="warning"
          size="small"
          plain
          icon="el-icon-download"
          v-if="permission.terminal_export"
          @click="handleExport"
          >导出
        </el-button>
      </template> -->
      <template slot-scope="scope" slot="menu">
        <el-button
          icon="el-icon-picture-outline"
          size="small"
          type="text"
          @click.stop="getqrCodeUrl(scope.row.qrcodeUrl)">查看二维码
        </el-button>
        <el-button icon="el-icon-view" size="small" type="text" v-if="permissionList.viewBtn"
                   @click.stop="handleView(scope.row, scope.index)">查 看
        </el-button>
        <!--        <el-button icon="el-icon-edit" size="small" type="text" v-if="permissionList.editBtn"-->
        <!--                   @click.stop="handleEdit(scope.row, scope.index)">修 改-->
        <!--        </el-button>-->

        <!--        <el-button icon="el-icon-key" size="small" type="text" v-if="permissionList.delBtn"
                           @click.stop="rowDel(scope.row)">解 绑
                </el-button>-->
      </template>
    </avue-crud>
    <el-dialog
      title="数据导入"
      append-to-body
      :visible.sync="excelBox"
      width="555px"
    >
      <avue-form
        :option="excelOption"
        v-model="excelForm"
        :upload-after="uploadAfter"
      >
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>
    <!-- 新建 -->
    <el-dialog
      :title="terminalDialog.text"
      top="1%"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="terminalDialog.visible"
      v-if="terminalDialog.visible"
      :before-close="terminalDialogHandleClose"
      ref="terDialog"
    >
      <!-- <terminalDialog  ref="terminalDialog" :terminalDialog="terminalDialog" :terminalDialogForm="terminalDialogForm"/> -->
      <terminalDialog ref="terminalDialog" :terminalDialog="terminalDialog" :rptNoList="rptNoList"
                      :serviceNoList="serviceNoList" :terminalDForm="terminalDForm"/>
      <span slot="footer" class="dialog-footer">
        <el-button
          @click="() => { terminalDialog.visible = false; this.$refs['terminalDialog'].initEmpty();}">取 消</el-button>
        <el-button type="primary" @click="terminalDialogSubmit" v-if="!terminalDialog.disabled">确 定</el-button>
      </span>
    </el-dialog>

    <el-image-viewer
      style="z-index: 2048"
      v-if="payVoucherDialog"
      :on-close="()=>{ payVoucherDialog = false }"
      :url-list="[rqUrlImage]"
    ></el-image-viewer>
  </basic-container>
</template>

<script>
import {
  getList,
  getDetail,
  add,
  update,
  remove,
  terminalSubmit,
  getRptNo, getRpsNo, getrpmNo, getrpiNo, getstoreNo, getrpstNo, getServiceList
} from "@/api/rb-core/terminal/terminal";
import {mapGetters} from "vuex";
import {getToken} from "@/util/auth";
import terminalDialog from "./terminalDialog";

export default {
  components: {
    terminalDialog
  },
  data() {
    return {
      payVoucherDialog: false,
      rqUrlImage: [],
      form: {},
      query: {},
      search: {},
      loading: true,
      excelBox: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      option: {
        height: "auto",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        selection: true,
        searchMenuSpan: 6,
        columnBtn: false,
        addBtn: false,//取消表格 新建/添加
        editBtn: false,
        viewBtn: false,
        delBtn: false,
        viewTitle: '修 改',
        labelWidth: 100,
        column: [
          {
            label: "终端简称",
            prop: "rtName",
            type: "input",
            sortable: true,
            display: false,
            overHidden: true,
          },
          {
            label: "类型",
            prop: "rptName",
            type: "input",
            sortable: true,
            display: false,
            overHidden: true,
          },
          {
            label: "类型",
            prop: "rptNo",
            type: "select",
            sortable: true,
            search: true,
            searchOrder: 1,
            filterable: true,
            hide: true,
            display: false,
            rules: [
              {
                required: true,
                message: "请输入类型",
                trigger: "blur",
              },
            ],
            props: {
              label: 'rptName',
              value: 'rptNo'
            },
            dicData: [],
            // change: (value) => {
            //   if (value) {
            //     // 获取供应商
            //     this.search.rpsNo = '';
            //     this.rpsNoList = [];
            //     this.search.rpmNo = '';
            //     this.rpmNoList = [];
            //     if (value.value) {
            //       getRpsNo(-1, -1, {rptNo: value.value}).then((res) => {
            //         this.rpsNoList = res.data.data.records;
            //         const column = this.findObject(this.option.column, "rpsNo");
            //         column.dicData = this.rpsNoList;
            //       })
            //     }
            //   }
            // },
            overHidden: true,
          },
          {
            label: "供应商",
            prop: "rpsName",
            type: "input",
            sortable: true,
            display: false,
            overHidden: true,
          },
          {
            label: "供应商",
            prop: "rpsNo",
            type: "select",
            sortable: true,
            search: true,
            searchOrder: 2,
            filterable: true,
            hide: true,
            display: false,
            rules: [
              {
                required: true,
                message: "请输入供应商名称",
                trigger: "blur",
              },
            ],
            props: {
              label: 'rpsName',
              value: 'rpsNo',
              desc: 'rpsNo'
            },
            dicUrl: `/api/rb-core/core/terminal/terminal/supList?current=-1&size=-1`,
            dicFormatter: (data) => {
              return data.data.records
            },
            // dicData: [],
            // change: (value) => {
            //   if (value) {
            //     // 获取型号
            //     this.search.rpmNo = '';
            //     this.rpmNoList = [];
            //     if (value.value) {
            //       getrpmNo(-1, -1, {rpmRpsNo: value.value}).then((res) => {
            //         this.rpmNoList = res.data.data.records;
            //         const column = this.findObject(this.option.column, "rpmNo");
            //         column.dicData = this.rpmNoList;
            //       })
            //     }
            //   }
            // },
            overHidden: true,
          },
          {
            label: "型号",
            prop: "rpmName",
            type: "input",
            sortable: true,
            display: false,
            overHidden: true,
          },
          {
            label: "型号",
            prop: "rpmNo",
            type: "select",
            sortable: true,
            search: true,
            filterable: true,
            searchOrder: 3,
            hide: true,
            display: false,
            rules: [
              {
                required: true,
                message: "请输入型号",
                trigger: "blur",
              },
            ],
            props: {
              label: 'rpmName',
              value: 'rpmNo',
              desc: 'rpmNo'
            },
            dicUrl: `/api/rb-core/core/terminal/terminal/modelList?current=-1&size=-1`,
            dicFormatter: (data) => {
              return data.data.records
            },
            // dicData: [],
            overHidden: true,
          },
          {
            label: "服务商",
            prop: "serviceName",
            type: "input",
            sortable: true,
            display: false,
            overHidden: true,
            minWidth:180,
          },
          {
            label: "服务商",
            prop: "serviceNo",
            type: "select",
            filterable: true,
            sortable: true,
            search: true,
            searchOrder: 4,
            hide: true,
            display: false,
            props: {
              label: 'serviceName',
              value: 'serviceNo',
              desc: 'serviceNo'
            },
            dicData: [],
            // change: (value) => {
            //   if (value) {
            //     this.search.rpiNo = '';
            //     this.rpiNoList = [];
            //     this.search.storeNo = '';
            //     this.storeNoList = [];
            //     this.search.rpstNo = '';
            //     this.rpstNoList = [];
            //     if (value.value) {
            //       getrpiNo(-1, -1, {serveNo: value.value}).then((res) => {
            //         this.rpiNoList = res.data.data.records;
            //         const column = this.findObject(this.option.column, "rpiNo");
            //         column.dicData = this.rpiNoList;
            //       })
            //     }
            //   }
            // },
            overHidden: true,
          },
          {
            label: "商户",
            prop: "rpiName",
            type: "input",
            sortable: true,
            display: false,
            overHidden: true,
            minWidth:180,
          },
          {
            label: "商户",
            prop: "rpiNo",
            type: "select",
            filterable: true,
            sortable: true,
            search: true,
            searchOrder: 4,
            hide: true,
            display: false,
            rules: [
              {
                required: true,
                message: "请输入商户",
                trigger: "blur",
              },
            ],
            props: {
              label: 'rpiName',
              value: 'rpiNo',
              desc: 'rpiNo'
            },
            dicUrl: `/api/rb-core/core/terminal/terminal/posInfoList?current=-1&size=-1`,
            dicFormatter: (data) => {
              return data.data.records
            },
            // dicData: [],
            // change: (value) => {
            //   if (value) {
            //     this.search.storeNo = '';
            //     this.storeNoList = [];
            //     this.search.rpstNo = '';
            //     this.rpstNoList = [];
            //     if (value.value) {
            //       getstoreNo(-1, -1, {rpiNo: value.value}).then((res) => {
            //         this.storeNoList = res.data.data.records;
            //         const column = this.findObject(this.option.column, "storeNo");
            //         column.dicData = this.storeNoList;
            //       })
            //     }
            //   }
            // },
            overHidden: true,
          },
          {
            label: "门店",
            prop: "storeName",
            type: "input",
            sortable: true,
            display: false,
            overHidden: true,
            minWidth:180,
          },
          {
            label: "门店",
            prop: "storeNo",
            type: "select",
            sortable: true,
            filterable: true,
            search: true,
            searchOrder: 5,
            hide: true,
            display: false,
            rules: [
              {
                required: true,
                message: "请输入门店",
                trigger: "blur",
              },
            ],
            props: {
              label: 'rpsName',
              value: 'rpsNo',
              desc: 'rpsNo'
            },
            dicUrl: `/api/rb-core/core/terminal/terminal/storeList?current=-1&size=-1`,
            dicFormatter: (data) => {
              return data.data.records
            },
            // dicData: [],
            // change: (value) => {
            //   if (value) {
            //     this.search.rpstNo = '';
            //     this.rpstNoList = [];
            //     if (value.value) {
            //       getrpstNo(-1, -1, {rpsNo: value.value}).then((res) => {
            //         this.rpstNoList = res.data.data.records;
            //         const column = this.findObject(this.option.column, "rpstNo");
            //         column.dicData = this.rpstNoList;
            //       })
            //     }
            //   }
            // },
            overHidden: true,
          },
          {
            label: "收银员",
            prop: "rpstName",
            type: "input",
            sortable: true,
            display: false,
            overHidden: true,
          },
          {
            label: "收银员",
            prop: "rpstNo",
            type: "select",
            sortable: true,
            filterable: true,
            search: true,
            searchOrder: 6,
            searchLabelWidth: 94,
            hide: true,
            display: false,
            rules: [
              {
                required: true,
                message: "请输入收银员",
                trigger: "blur",
              },
            ],
            props: {
              label: 'rpstName',
              value: 'rpstNo',
              desc: 'rpstNo'
            },
            dicUrl: `/api/rb-core/core/terminal/terminal/staffList?current=-1&size=-1`,
            dicFormatter: (data) => {
              return data.data.records
            },
            dicData: [],
            overHidden: true,
          },
          {
            label: "SN",
            prop: "rsSn",
            type: "input",
            sortable: true,
            search: true,
            rules: [
              {
                required: true,
                message: "请输入SN",
                trigger: "blur",
              },
            ],
            overHidden: true,
          },
          {
            label: "绑定时间",
            prop: "createTime",
            type: "input",
            search: true,
            rules: [
              {
                required: true,
                message: "请输入SN",
                trigger: "blur",
              },
            ],
            display:false,
            overHidden: true
          }
          
        ]
      },
      data: [],
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "模板上传",
            prop: "excelFile",
            type: "upload",
            drag: true,
            loadText: "模板上传中，请稍等",
            span: 24,
            propsHttp: {
              res: "data",
            },
            tip: "请上传 .xls,.xlsx 标准格式文件",
            action: "/api/rb-core/terminal/terminal/import",
          },
          {
            label: "模板下载",
            prop: "excelTemplate",
            formslot: true,
            span: 24,
          },
        ],
      },
      terminalDialog: {
        disabled: false,
        visible: false,
        type: 'add',
        text: '新建'
      },//表格右侧操作add,edit,view
      terminalDForm: {},//终端表单
      rptNoList: [],//类型
      rpsNoList: [],//供应商名称
      rpmNoList: [],//型号
      rpiNoList: [],//商户号
      storeNoList: [],//门店
      rpstNoList: [],//收银员
      serviceNoList: [],//服务商
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.terminal_add, false),
        viewBtn: this.vaildData(this.permission.terminal_view, false),
        delBtn: this.vaildData(this.permission.terminal_delete, false),
        editBtn: this.vaildData(this.permission.terminal_edit, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
  },
  watch: {
    // 'search.rptNo'(newVal, oldVal) {
    //     if (newVal !== oldVal) {
    //       this.search.rpsNo = '';
    //       const rpsNo = this.findObject(this.option.column, "rpsNo");
    //       rpsNo.dicData = [];
    //       this.search.rpmNo = '';
    //       const rpmNo = this.findObject(this.option.column, "rpmNo");
    //       rpmNo.dicData = [];
    //     }
    //   },
  },
  methods: {
    // 新建
    handleSave() {
      this.terminalDialog.visible = true;
      this.terminalDialog.type = 'add';
      this.terminalDialog.text = "新建终端";
      this.terminalDialog.disabled = false;
    },
    // 编辑
    handleEdit(row) {
      this.terminalDialog.visible = true;
      this.terminalDialog.type = 'edit';
      this.terminalDialog.text = "修改终端";
      this.terminalDialog.disabled = false;
      this.terminalDForm = JSON.parse(JSON.stringify(row));
    },
    getqrCodeUrl(qrcodeUrl) {
      this.rqUrlImage[0] = qrcodeUrl;
      this.payVoucherDialog = true;
    },
    handleView(row) {
      this.terminalDialog.visible = true;
      this.terminalDialog.type = 'view';
      this.terminalDialog.text = "查看";
      this.terminalDialog.disabled = true;
      this.terminalDForm = JSON.parse(JSON.stringify(row));
    },
    // 保存
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm("确定将选择数据解绑?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据解绑?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query, {eqType: 1})
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    handleImport() {
      this.excelBox = true;
    },
    handleExport() {
      let exQuery = ``;
      exQuery += `&rtName=${this.search.rtName}`;
      exQuery += `&rtNo=${this.search.rtNo}`;
      exQuery += `&rpsNo=${this.search.rpsNo}`;
      exQuery += `&rptNo=${this.search.rptNo}`;
      exQuery += `&rpmNo=${this.search.rpmNo}`;
      // exQuery += `&rsSn=${this.search.rsSn}`;
      exQuery += `&rpiNo=${this.search.rpiNo}`;
      exQuery += `&storeNo=${this.search.storeNo}`;
      exQuery += `&rpstNo=${this.search.rpstNo}`;
      exQuery += `&rtPara=${this.search.rtPara}`;
      exQuery += `&isOn=${this.search.isOn}`;
      this.$confirm("是否导出用户数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        window.open(
          `/api/rb-core/core/terminal/terminal/export?${
            this.website.tokenHeader
          }=${getToken()}` + exQuery
        );
      });
    },
    handleTemplate() {
      window.open(
        `/api/rb-core/core/terminal/terminal/export-template?${
          this.website.tokenHeader
        }=${getToken()}`
      );
    },
    uploadAfter(res, done) {
      this.excelBox = false;
      this.refreshChange();
      done();
    },
    sortChange(val) {
      if (val.order == "ascending") {
        //正序
        this.query.ascs = val.prop;
        this.query.descs = "";
      } else {
        //倒序
        this.query.descs = val.prop;
        this.query.ascs = "";
      }
      this.refreshChange();
    },
    // 终端---新建弹框 关闭前回调
    terminalDialogHandleClose(done) {
      this.$refs['terminalDialog'].initEmpty();
      done();
    },
    // 终端---新建弹框提交
    terminalDialogSubmit() {
      /**
       * add  新建
       * edit 修改
       * view 查看详情
       */
      if (this.terminalDialog.type !== 'view') {
        this.$refs['terminalDialog'].$refs['terminalDialogForm'].validate((valid) => {
          if (valid) {
            let form = this.$refs['terminalDialog'].terminalDialogForm;
            // -----add---str---
            let rtPara = {}
            form.rtParaList.map(itm => {
              rtPara[itm.key] = itm.val;
            })
            form.rtPara = JSON.stringify(rtPara)
            // -----add---end---

            let param = {
              ...this.$refs['terminalDialog'].terminalDialogForm
            }
            terminalSubmit(param).then(() => {
                this.onLoad(this.page);
                this.$refs['terminalDialog'].initEmpty();

                this.$message({
                  type: "success",
                  message: "操作成功!",
                });
                // setTimeout(() => {
                this.terminalDialog.visible = false;
                // }, 1500);

              },
              (error) => {
                window.console.log(error);
              }
            );
          }
        });

      }
    },
    // 获取 类型名称
    requestRptNo() {
      getRptNo(-1, -1,{eqType:1}).then((res) => {
        this.rptNoList = res.data.data.records;
        const column = this.findObject(this.option.column, "rptNo");
        column.dicData = this.rptNoList;
      })
    },
    // 获取 商户
    // requestrpiNo(){
    // getrpiNo(-1,-1).then((res)=>{
    //   this.rpiNoList = res.data.data.records;
    //   const column = this.findObject(this.option.column, "rpiNo");
    //   column.dicData = this.rpiNoList;
    // })
    // },
    // 获取 服务商
    apiServiceList() {
      getServiceList().then((res) => {
        this.serviceNoList = res.data.data.records;
        const column = this.findObject(this.option.column, "serviceNo");
        column.dicData = this.serviceNoList;
      })
    },
    initRequest() {
      this.requestRptNo();//获取 类型
      this.apiServiceList();//获取 服务商
    }
  },
  created() {
    this.initRequest()
  },
};
</script>

<style>
</style>
